package org.advanced.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * @author John.zhang
 * @version Id: NioSocketServer, v 1.0 2020/12/17 11:10 ZhiYong Exp $
 */
public class NioSocketServer {

    public static void main(String[] args) {
        try {
            //可以支持两种模式：阻塞、非阻塞
            ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
            //默认是true阻塞的，解决连接阻塞
            serverSocketChannel.configureBlocking(false);
            serverSocketChannel.socket().bind(new InetSocketAddress(8080));
            while (true){
                //设置configureBlocking后这里不再阻塞
                SocketChannel socketChannel = serverSocketChannel.accept();
                if(socketChannel!=null){
                    ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                    socketChannel.read(byteBuffer);
                    System.out.println(new String(byteBuffer.array()));
                    //把消息写回到客户端
                    Thread.sleep(1000);
                    //byteBuffer.flip();
                    ByteBuffer byteBuffer2 = ByteBuffer.allocate(1024);
                    byteBuffer2.put("Hello I'm server Channel".getBytes());
                    byteBuffer2.flip();
                    socketChannel.write(byteBuffer2);
                }else {
                    Thread.sleep(1000);
                    System.out.println("没有客户端连接过来");
                }

            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }

}
